<?php

namespace addons\booking\model;

use think\Model;
use think\Db;

class OrderGoods extends Model
{

    // 表名
    protected $name = 'booking_order_goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'image_text'
    ];

    public function getImageTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['image']) ? $data['image'] : '');
        return cdnurl($value, true);
    }

    public function Goods()
    {
        return $this->hasOne('Goods', 'id', 'goods_id');
    }

    //销量增
    public static function setGoodsSalesInc($orderid)
    {
        $list = (new self)->where('orderid', $orderid)->select();
        // 启动事务
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $goods = $item->goods;
                if ($goods) {
                    $goods->setInc('sales', $item->nums);
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return true;
    }

    //销量减
    public static function setGoodsSalesDec($orderid)
    {
        $list = (new self)->where('orderid', $orderid)->select();
        // 启动事务
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $goods = $item->goods;
                if ($goods) {
                    $goods->setDec('sales', $item->nums);
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return true;
    }
}
